library("xgboost")
library("Matrix")

train <- read.table("train_TPM_UCEC.txt", header = T, sep = "\t", check.names = F,
    row.names = 1)
y <- train$Subtype
# 基因名字不能有横杠
test_matrix <- sparse.model.matrix(Subtype ~ . - 1, data = train)
train_fin <- list(data = test_matrix, label = y)

dtrain <- xgb.DMatrix(data = train_fin$data, label = train_fin$label)

xgb <- xgboost(data = dtrain, eta = 0.3, objective = "binary:logistic", nround = 25)
importance <- xgb.importance(test_matrix@Dimnames[[2]], model = xgb)
head(importance)
xgb.ggplot.importance(importance)
write.table(importance, "importance.txt", sep = "\t", quote = F, col.names = F)





# install.packages('pROC') install.packages('glmnet')
library(glmnet)

# 多指标的ROC曲线
logistic_data <- read.csv("1.csv", row.names = 1)
subtype = read.table("subtype.txt", header = T, sep = "\t", check.names = F, row.names = 1)
identical(stringr::str_sub(row.names(logistic_data), 1, 16), row.names(subtype))
# 建立Logistic回归模型
x = log2(logistic_data + 1)
x1 <- as.matrix(x)
y = subtype$Group

cvfit = cv.glmnet(x1, y, family = "binomial", alpha = 1, type.measure = "auc")

# 利用建立的Logistic回归模型，对数据进行预测
prob1 <- predict(cvfit, newx = x1, type = "response")

library(ROCR)
# 绘制预测结果的ROC曲线，计算曲线下面积AUC值
predic1 <- prediction(prob1, y)

auc_min = performance(predic1, "auc")@y.values[[1]]
perf_min <- performance(predic1, "tpr", "fpr")
plot(perf_min, colorize = FALSE, col = "blue")
lines(c(0, 1), c(0, 1), col = "gray", lty = 4)
text(0.8, 0.2, labels = paste0("AUC = ", round(auc_min, 3)))


